import URL from '../config/URL'
import crypt from './crypt'

const {
  server
} = URL

function getCaptchaUrl({ params = {} } = {}) {
  let q = {
    openid: global.openid,
    api: 'getCaptcha',
    ...params
  }
  q = encodeURIComponent(crypt.encrypt(q))
  return `${server}?q=${q}`
}

function trim(str) {
  if (typeof str !== 'string') {
    return str
  }
  return str.replace(/^\s*/g, '').replace(/\s*$/g, '')
}

function makeid() {
  let text = ""
  const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

  for(let i = 0; i < 5; i++) {
    text = `${text}${possible.charAt(Math.floor(Math.random() * possible.length))}`
  }
  return text
}

function vibrate() {
  if (wx.vibrateLong) {
    wx.vibrateLong()
  } else if (wx.vibrateShort){
    wx.vibrateShort()
  }
}

export default {
  getCaptchaUrl,
  trim,
  makeid,
  vibrate
}
